const myUtils = require("../../utils/myUtils");
const wxCharts = require('../../utils/wxcharts.js');
let ui;
// const XLSX=require('node-xlsx')
// const ui={
//   openId:500
// }
Page({
  data: {
    admin: false,
    userInfo: {},
    userInfos: [],
    ques: null,
    ques_info: null,
    names: [],
    sexs: ["不限", "男", "女"],
    classes: ["不限"],
    grades: ["不限"],
    questions: [],
    times: [],
    dateNums: [],
    answerDaily: [],
    nameIndex: 0,
    sexIndex: 0,
    classIndex: 0,
    gradeIndex: 0,
    questionIndex: 0,
    timeBeginIndex: 0,
    timeEndIndex: 0,
    exist: true,
    currentAnswers: [],
    fileUrl: "",
    fileName: "",
    allData: [],
    beginDateValue: null,
    endDateValue: null,
    time: null,
    date: null,
    initComplete: false,
    tip:null,
    tips:[],
  },
  //获取云存储文件下载地址，这个地址有效期一天
  getFileUrl: async function (fileID) {
    let that = this;
    let res = await wx.cloud.callFunction({
      name: "get_file_url",
      data: {

        fileID: fileID
      }
    });
    let fileUrl = res.result;
    fileUrl += "?t=" + new Date().getTime();
    that.setData({
      fileUrl: fileUrl
    });
  },
  exportToExcel: async function (e) {
    let type = e.currentTarget.dataset.type;
    let _this = this;
    let url;
    let res
    console.log("类型:", type);
    console.log(this.data.fileName);
    if (this.data.fileName === "") {
      this.setData({
        fileName: "未命名"
      });
    }

    if (this.data.dateNums[this.data.timeBeginIndex] > this.data.dateNums[this.data.timeEndIndex]) {
      wx.showModal({
        title: '警告',
        content: '您的开始日期晚于结束日期!',
        showCancel: false,
        confirmText: '知道了',
      });
      return;
    }
    if (type === "cur") {
      let curData = {
        questionName: _this.data.questionName,
        avgData: _this.data.avgData,
        standardDeviationData: _this.data.standardDeviationData,
        categories: _this.data.categories,
      }
      res = await wx.cloud.callFunction({
        name: "excel",

        data: {
          type: type,
          fileName: _this.data.fileName,
          data: {

            nameFilter: _this.data.nameFilter,
            sexFilter: _this.data.sexFilter,
            classFilter: _this.data.classFilter,
            gradeFilter: _this.data.gradeFilter,
            allData: [curData],
          },

        }
      })
    } else {
      let allData = this.getAllData();
      res = await wx.cloud.callFunction({
        name: "excel",
        data: {
          type: type,
          data: {

            nameFilter: "所有人",
            sexFilter: "不限",
            classFilter: "不限",
            gradeFilter: "不限",
            allData: allData,
          },
          fileName: _this.data.fileName
        }
      })
    }
    console.log(res);
    await this.getFileUrl(res.result.fileID);
    this.setUrlToClipboard();
  },
  setUrlToClipboard: async function () {

    wx.setClipboardData({
      data: this.data.fileUrl,
    }).then(res => {
      wx.getClipboardData({}).then(resp => {
        wx.showModal({
          title: '提示',
          content: '下载地址已复制到剪切板!',
          showCancel: false,
          confirmText: '好的',
        });
        console.log("复制成功", resp.data) // data
      });
    })
  },
  getUserInfoByOpenId: function (openId) {
    console.log("userInfos", this.data.userInfos);
    for (let info of this.data.userInfos) {
      if (info.openId === openId) {
        return info;
      }
    }
    return null;
  },
  checkUserInfo(userInfo) {
    console.log("userInfo", userInfo);
    // userInfo=null;
    let nameFilter = this.data.names[this.data.nameIndex];
    let sexFilter = this.data.sexs[this.data.sexIndex];
    let classFilter = this.data.classes[this.data.classIndex];
    let gradeFilter = this.data.grades[this.data.gradeIndex];
    // let nameFilter=this.data.names[this.data.nameIndex];
    console.log(classFilter);
    console.log(userInfo.class);
    console.log(userInfo.class === classFilter);
    let flag = true;
    if (nameFilter !== "所有人" && nameFilter !== userInfo.name) {
      console.log("名称不符合要求");
      flag = false;
    }
    if (sexFilter !== "不限" && sexFilter !== userInfo.sex) {
      console.log("性别不符合要求");
      flag = false;
    }
    if (classFilter !== "不限" && classFilter !== userInfo.class) {
      console.log("班级不符合要求");
      flag = false;
    }
    if (gradeFilter !== "不限" && gradeFilter !== userInfo.grade) {
      console.log("年级不符合要求");
      flag = false;
    }
    return flag;

  },
  changeRadioTextIntoValue(radioText) {
    let value = 0;
    if (radioText === "未上课/未学习"|| radioText === "很弱") {
      value = 0;
    } else if (radioText === "经常" || radioText === "完全不符合" || radioText === "弱") {
      value = 1;
    } else if (radioText === "有时" || radioText === "较不符合" || radioText === "一般") {
      value = 2;
    } else if (radioText === "一般" || radioText === "一般"|| radioText === "强" ) {
      value = 3;
    } else if (radioText === "很少" || radioText === "较符合" || radioText === "很强") {
      value = 4;
    } else if (radioText === "没有" || radioText === "完全符合" ) {
      value = 5;
    }
    return value;
  },
  drawChart: async function () {
    let chartData;
    if (this.data.admin) {
      chartData = await this.prepareChartDataForAdmin();
    } else {
      chartData = await this.prepareChartDataForUser();
    }
    if(chartData==null){
      return;
    }
    //准备绘制折线图
    // 获取设备屏幕宽度
    var windowWidth = wx.getSystemInfoSync().windowWidth;

    if (this.data.admin) {
      //将数据保存到data，方便导出
      let nameFilter = this.data.names[this.data.nameIndex];
      let sexFilter = this.data.sexs[this.data.sexIndex];
      let classFilter = this.data.classes[this.data.classIndex];
      let gradeFilter = this.data.grades[this.data.gradeIndex];
      this.setData({
        categories: chartData.categories,
        standardDeviationData: chartData.standardDeviationData,
        avgData: chartData.avgData,
        questionName: chartData.currentQuestionText,
        nameFilter: nameFilter,
        sexFilter: sexFilter,
        classFilter: classFilter,
        gradeFilter: gradeFilter,
      });
    }
    let series;
    if(this.data.admin){
      series=[{
        name: "平均值+标准差",
        data: chartData.upData, // 折线图数据
        color: '#00ff00',
        format: function (val) {
          return val;
        }
      }, {
        name: "平均值-标准差",
        data: chartData.downData, // 折线图数据
        color: '#00ff00',
        format: function (val) {
          return val;
        }
      }, {
        name: chartData.lineName,
        data: chartData.avgData, // 折线图数据
        format: function (val) {
          return val;
        }
      }];

    }
    else{
      series=[{
        name: chartData.lineName,
        data: chartData.curData, // 折线图数据
        color: "",
        format: function (val) {
          return val;
        }
      }];
    }

    // 初始化折线图
    this.lineChart = new wxCharts({
      canvasId: 'lineCanvas', // 与 WXML 中 canvas 的 canvas-id 保持一致
      type: 'line', // 图表类型为折线图
      categories: chartData.categories, // 横坐标数据
      series: series,
      yAxis: {
        title: chartData.yAxisName,
        format: function (val) {
          return val;
        },
        min: chartData.yAxisMin,
        max: chartData.yAxisMax
      },
      width: windowWidth, // 根据屏幕宽度设置画布宽度
      height: 300 // 图表高度
    });
    //更改提示
    let currentQuestion=chartData.currentQuestion;
    let opts=[];
    if(currentQuestion.type!=="radio"){
      this.setData({
        tip:null
      });
      return;
    }
    for(let opt of currentQuestion.options){
      opts.push(opt);
    }
    let str="";
    for(let t of opts){
      str+=t;
      str+=","
    }
    str=str.slice(0,-1);
    let tip=`注：0-${opts.length-1}分分别代表${str}`;
    this.setData({
      tip:tip
    });

  },

  getAllData: function () {
    let dateNums = this.data.dateNums;
    let timeBeginIndex = this.data.timeBeginIndex;
    let timeEndIndex = this.data.timeEndIndex;
    let answerDaily = this.data.answerDaily;
    const timeBeginNum = dateNums[timeBeginIndex];
    const timeEndNum = dateNums[timeEndIndex];
    console.log(timeBeginNum);
    console.log(timeEndNum);
    console.log(dateNums);
    if (dateNums[timeBeginIndex] > dateNums[timeEndIndex]) {
      return;
    }
    console.log(answerDaily);

    //将日期开始到日期结束之间所有的答卷放进surveys
    let surveys = [];
    for (let ans of answerDaily) {
      // console.log("dateNum:"+ans.dateNum);
      if (ans.dateNum >= timeBeginNum && ans.dateNum <= timeEndNum) {
        surveys.push(ans);
      }
      if (ans.dateNum < timeBeginNum) {
        break;
      }
    }
    // console.log({...surveys});
    //升序排序
    surveys.sort((a, b) => {
      return a.dateNum - b.dateNum;
    });
    console.log({
      ...surveys
    });


    //=========
    //x坐标和y坐标
    //横坐标
    let categories = [];
    for (let sur of surveys) {
      let dateNum = sur.dateNum;
      let dateStr = dateNum.toString();
      let year = dateStr.slice(0, 4);
      let month = dateStr.slice(4, 6);
      let day = dateStr.slice(6, 8);
      categories.push(`${year}年${month}月${day}日`);
    }
    let allData = [];
    // let currentQuestionText = this.data.questions[this.data.questionIndex];

    for (let currentQuestionText of this.data.questions) {
      let currentQuestion;

      console.log(this.data.ques);
      for (let quest of this.data.ques) {
        if (quest.question === currentQuestionText) {
          currentQuestion = quest;
          break;
        }
      }
      console.log(currentQuestion);


      //数据处理，求平均数和方差
      let avgData = []; //平均值数据
      let standardDeviationData = []; //标准差数据
      console.log("surveys:", surveys);
      for (let survey of surveys) {
        let questionsCurDate = survey.data; //这一天所有的问卷
        let quesDate = survey.date;
        let sum = 0;
        let count = 0;
        let datas = [];
        let standardDeviation;
        console.log("questions:", questionsCurDate);
        for (let ques of questionsCurDate) {
          console.log("ques", ques);
          for (let ans of ques.answer) {
            if (ans.questionName === currentQuestionText) {
              let val;
              if (ans.type === "radio") {
                val = this.changeRadioTextIntoValue(ans.value);
              } else {
                val = ans.value;
              }
              datas.push(val);
              sum += val;
              count++;
              break;
            }

          }


        }
        let avg = 0;
        if (count === 0) {
          avg = 0;
          standardDeviation = 0;
        } else {
          avg = sum / count;
          console.log(datas);
          let variance = datas.reduce((a, b) => a + Math.pow(b - avg, 2), 0);
          standardDeviation = Math.sqrt(variance);
        }
        avgData.push(avg);
        standardDeviationData.push(standardDeviation);
      }
      console.log("avgData", avgData);
      console.log("standardDeviationData", standardDeviationData);
      let upData = [];
      let downData = [];
      for (let i in avgData) {
        upData.push(avgData[i] + standardDeviationData[i]);
        downData.push(avgData[i] - standardDeviationData[i]);
      }
      console.log("upData", upData);
      console.log("downData", downData);
      let oneData = {
        categories: categories,
        standardDeviationData: standardDeviationData,
        avgData: avgData,
        questionName: currentQuestionText,
      }
      allData.push(oneData);

    }
    console.log(allData);
    return allData;
  },


  prepareChartDataForAdmin: async function () {
    const chartData = await this.prepareChartData({
      radioLineName: "平均程度值",
      sliderLineName: "平均值",
      admin: true,
    });
    return chartData;
  },
  prepareChartDataForUser: async function () {
    const chartData = await this.prepareChartData({
      radioLineName: "程度值",
      sliderLineName: "值",
      admin: false,
    });
    return chartData;
  },




  prepareChartData: async function ({
    radioLineName,
    sliderLineName,
    admin
  }) {
    let dateNums = this.data.dateNums;
    let timeBeginIndex = this.data.timeBeginIndex;
    let timeEndIndex = this.data.timeEndIndex;
    let answerDaily = this.data.answerDaily;
    const timeBeginNum = dateNums[timeBeginIndex];
    const timeEndNum = dateNums[timeEndIndex];
    let yAxisName;
    let yAxisMin;
    let yAxisMax;
    let lineName;
    console.log(timeBeginNum);
    console.log(timeEndNum);
    this.setData({
      exist: true
    });
    console.log(dateNums);
    //结束日期大于开始日期时，直接不绘制
    if (dateNums[timeBeginIndex] > dateNums[timeEndIndex]) {
      this.setData({
        exist: false
      });
      return null;
    }
    console.log(answerDaily);

    //将日期开始到日期结束之间所有的答卷放进surveys
    let surveys = [];
    for (let ans of answerDaily) {
      // console.log("dateNum:"+ans.dateNum);
      if (ans.dateNum >= timeBeginNum && ans.dateNum <= timeEndNum) {
        surveys.push(ans);
        console.log("surveys:");
        console.log({
          ...surveys
        });
      }
      if (ans.dateNum < timeBeginNum) {
        break;
      }
    }
    // console.log({...surveys});
    //升序排序
    surveys.sort((a, b) => {
      return a.dateNum - b.dateNum;
    });
    console.log({
      ...surveys
    });


    //=========
    //x坐标和y坐标
    //横坐标
    let categories = [];
    for (let sur of surveys) {
      let dateNum = sur.dateNum;
      let dateStr = dateNum.toString();
      let year = dateStr.slice(0, 4);
      let month = dateStr.slice(4, 6);
      let day = dateStr.slice(6, 8);
      categories.push(`${month}${day}`); //0418
    }
    let currentQuestionText = this.data.questions[this.data.questionIndex];
    let currentQuestion;

    console.log(this.data.ques);
    for (let quest of this.data.ques) {
      if (quest.question === currentQuestionText) {
        currentQuestion = quest;
        break;
      }
    }
    console.log(currentQuestion);

    if (currentQuestion.type === "radio") {
      yAxisName = `程度值（0-${currentQuestion.options.length-1}分）`;
      yAxisMin = 0;
      yAxisMax = 5;
      lineName = radioLineName;
    } else if (currentQuestion.type === "slider") {
      yAxisMin = currentQuestion.sliderMin;
      yAxisMax = currentQuestion.sliderMax + 5;
      yAxisName = "值";
      lineName = sliderLineName
    } else {
      throw new Error("未预料到的错误!");
    }


    //数据处理，普通用户求自己，管理员求平均数和方差
    let curData = [];
    let avgData = []; //平均值数据
    let standardDeviationData = []; //标准差数据
    let upData = [];
    let downData = [];
    if (admin === false) {

      console.log("surveys:", surveys);
      for (let survey of surveys) {
        let questionsCurDate = survey.data; //这一天所有的问卷
        let quesDate = survey.date;
        let val = 0;
        console.log("questions:", questionsCurDate);
        for (let ques of questionsCurDate) {

          console.log("ques", ques);
          console.log(this.data);
          console.log(this.data.userInfo);
          if (ques.openId !== this.data.userInfo.openId) {
            continue;
          }
          for (let ans of ques.answer) {
            if (ans.questionName === this.data.questions[this.data.questionIndex]) {
              val = 0;
              if (ans.type === "radio") {
                val = this.changeRadioTextIntoValue(ans.value);
              } else {
                val = ans.value;
              }

              break;
            }
          }
        }
        curData.push(val);
      }
      console.log("curData", curData);
    } else {


      console.log("surveys:", surveys);
      for (let survey of surveys) {
        let questionsCurDate = survey.data; //这一天所有的问卷
        let quesDate = survey.date;
        let sum = 0;
        let count = 0;
        let datas = [];
        let standardDeviation;
        console.log("questions:", questionsCurDate);
        for (let ques of questionsCurDate) {
          console.log("ques", ques);
          try {
            let userInfo = this.getUserInfoByOpenId(ques.openId);


            let flag = this.checkUserInfo(userInfo);

            console.log("判断是否为符合条件的问卷", flag);
            if (flag == false) {
              continue;
            }

          } catch (error) {
            console.error("获取用户信息时出错：", error);
            continue;
          }

          for (let ans of ques.answer) {
            if (ans.questionName === this.data.questions[this.data.questionIndex]) {
              let val;
              if (ans.type === "radio") {
                val = this.changeRadioTextIntoValue(ans.value);
              } else {
                val = ans.value;
              }
              datas.push(val);
              sum += val;
              count++;
              break;
            }

          }


        }
        let avg = 0;
        if (count === 0) {
          avg = 0;
          standardDeviation = 0;
        } else {
          avg = sum / count;
          console.log(datas);
          let variance = datas.reduce((a, b) => a + Math.pow(b - avg, 2), 0);
          standardDeviation = Math.sqrt(variance);
        }
        avgData.push(avg);
        standardDeviationData.push(standardDeviation);
      }
      console.log("avgData", avgData);
      console.log("standardDeviationData", standardDeviationData);

      for (let i in avgData) {
        upData.push(avgData[i] + standardDeviationData[i]);
        downData.push(avgData[i] - standardDeviationData[i]);
      }
      console.log("upData", upData);
      console.log("downData", downData);

    }

    return{
      currentQuestionText:currentQuestionText,
      standardDeviationData:standardDeviationData,
      categories:categories,
      upData:upData,
      downData:downData,
      avgData:avgData,
      curData:curData,
      yAxisMin:yAxisMin,
      yAxisMax:yAxisMax,
      yAxisName:yAxisName,
      lineName:lineName,
      currentQuestion:currentQuestion,
    };
  },





  initData: async function () { //初始化数据
    //获取管理员权限
    let admin = await this.isAdmin()
    this.setData({
      admin: admin
    })
    if (this.data.admin) {
      await this.getUserInfos();
    }
    //获取每日问卷的数据
    let res = await wx.cloud.callFunction({
      name: "get_question",
      data: {
        questionName: "question_daily"
      }
    })
    let ques = res.result.data;
    console.log(ques);
    let questions = []
    for (let quest of ques) {
      questions.push(quest.question);
    }
    this.setData({
      ques: ques, //问卷
      questions: questions //题目文字
    });

    //获取回答数据
    res = await wx.cloud.callFunction({
      name: "get_answer_daily"
    });
    // console.log(res);
    this.setData({
      answerDaily: res.result.data
    });


    if (this.data.admin) {
      //获取个人信息问卷
      res = await wx.cloud.callFunction({
        name: "get_question",
        data: {
          questionName: "question_user_info"
        }
      })
      let ques_info = res.result.data;
      console.log(ques_info);

      this.setData({
        ques_info: ques_info
      })
    }
  },

  //初始化选项
  initSelectors: async function () {
    //日期
    let times = [];
    let dateNums = [];
    for (let ans of this.data.answerDaily) {
      let date = ans.date;
      let str = `${date.year}年${date.month}月${date.day}日`
      times.push(str);
      dateNums.push(ans.dateNum);
    }
    this.setData({
      times: times,
      dateNums: dateNums

    });
    let timeEndIndex = 0;
    let timeBeginIndex = Math.min(times.length - 1, timeEndIndex + 30);
    console.log(this.data.date);
    let date = this.data.date;
    let endDateValue = new Date(date.year, date.month - 1, date.day);
    let beginDateValue = endDateValue.toISOString().split('T')[0];
    endDateValue.setDate(endDateValue.getDate() - 30);
    endDateValue = endDateValue.toISOString().split('T')[0];
    console.log(beginDateValue);
    console.log(endDateValue);
    this.setData({
      beginDateValue: beginDateValue,
      endDateValue: endDateValue
    });

    this.setData({

      timeBeginIndex: timeBeginIndex,
      timeEndIndex: timeEndIndex,
    });
    if (this.data.admin) {
      for (let quest of this.data.ques_info) {
        if (quest.question == "您的年级是？") {
          let opt = quest.options;
          opt.unshift("不限");
          this.setData({
            grades: opt
          });
        } else if (quest.question == "您的班级是？") {
          let opt = quest.options;
          opt.unshift("不限");
          this.setData({
            classes: opt
          });
        }
      }
      console.log(this.data.userInfos);
      let names = ["所有人"];
      for (let info of this.data.userInfos) {
        names.push(info.name);
      }
      this.setData({
        names: names
      });
    }
  },
  onShow: async function () {
    this.setData({
      initComplete: false
    });
    ui = wx.getStorageSync("userInfo");
    //用户没登录则跳转
    if (ui == null || ui.openid == null) {
      wx.switchTab({
        url: '/pages/me/me',
      })
      await wx.showModal({
        title: '提示',
        content: '请先登录!',
        showCancel: false,
        confirmText: '知道了',
      });
      return;
    }
    const time = await myUtils.getTime();
    const date = {
      day: time.day,
      // day: 21,

      month: time.month,
      year: time.year
    };
    this.setData({
      time: time,
      date: date
    });
    var res = await wx.cloud.callFunction({
      name: "get_user_info",
      data: {
        openId: ui.openid
        // openId:123
      },
    });
    // console.log(res);
    if (res.result == null) {
      wx.switchTab({
        url: '/pages/me/me',
      })
      await wx.showModal({
        title: '提示',
        content: '请先填写个人信息!',
        showCancel: false,
        confirmText: '知道了',
      });
      return;
    }
    this.setData({
      userInfo: res.result
    });
    console.log("用户信息：", this.data.userInfo);


    await this.initData();
    await this.initSelectors();
    this.drawChart();
    this.setData({
      initComplete: true
    });
  },
  isAdmin: async function () {
    let res = await wx.cloud.callFunction({
      name: "is_admin"
    });
    console.log(res);
    return res.result;
  },
  getUserInfos: async function () {
    let res = await wx.cloud.callFunction({
      name: "get_user_info"
    });
    console.log(res);
    this.setData({
      userInfos: res.result
    })
  },
  bindBeginDateChange(e) {
    console.log(e);
    this.setData({
      beginDateValue: e.detail.value
    });
  },
  bindEndDateChange(e) {
    console.log(e);
    this.setData({
      endDateValue: e.detail.value
    });
  },
  bindNameChange(e) {
    let index = e.detail.value;
    this.setData({
      nameIndex: index
    })
    this.drawChart();
  },
  bindSexChange(e) {
    let index = e.detail.value;
    this.setData({
      sexIndex: index
    })
    this.drawChart();
  },
  bindClassChange(e) {
    let index = e.detail.value;
    this.setData({
      classIndex: index
    })
    this.drawChart();
  },
  bindGradeChange(e) {
    let index = e.detail.value;
    this.setData({
      gradeIndex: index
    })
    this.drawChart();
  },
  bindQuestionChange(e) {
    let index = e.detail.value;
    this.setData({
      questionIndex: index
    })
    this.drawChart();
  },
  bindTimeBeginChange(e) {
    let index = e.detail.value;
    this.setData({
      timeBeginIndex: index
    })
    this.drawChart();
  },
  bindTimeEndChange(e) {
    let index = e.detail.value;
    this.setData({
      timeEndIndex: index
    })
    this.drawChart();
  },
  onInputFileNameChange(e) {
    // console.log(e);
    this.setData({
      fileName: e.detail.value
    })
  }





});